"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Plus } from "lucide-react"
import { User } from "@/types/admin"
import { columns } from "./columns"
import { DataTable } from "@/components/common/data-table"
import { UserDialog } from "@/components/admin/user-dialog"
import { DeleteDialog } from "@/components/admin/delete-dialog"
import { useAdminStore } from "@/lib/store"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"

export default function UsersPage() {
  const { users, deleteUser } = useAdminStore()
  
  const [openAddEditDialog, setOpenAddEditDialog] = useState(false)
  const [openDeleteDialog, setOpenDeleteDialog] = useState(false)
  const [selectedUser, setSelectedUser] = useState<User | undefined>(undefined)

  const handleAddUser = () => {
    setSelectedUser(undefined)
    setOpenAddEditDialog(true)
  }

  const handleEditUser = (user: User) => {
    setSelectedUser(user)
    setOpenAddEditDialog(true)
  }

  const handleDeleteClick = (user: User) => {
    setSelectedUser(user)
    setOpenDeleteDialog(true)
  }

  const handleConfirmDelete = () => {
    if (selectedUser) {
      deleteUser(selectedUser.id)
      setOpenDeleteDialog(false)
    }
  }
  
  return (
    <div className="space-y-8">
      <Card className="card-shadow">
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle className="text-xl font-bold">用户管理</CardTitle>
          <Button onClick={handleAddUser} className="rounded-lg bg-primary hover:bg-primary/90">
            <Plus className="mr-2 h-4 w-4" /> 新增用户
          </Button>
        </CardHeader>
        <CardContent>
          <p className="text-muted-foreground mb-4">管理系统中的所有用户账户。</p>
          <DataTable 
            columns={columns({ 
              onEdit: handleEditUser, 
              onDelete: handleDeleteClick 
            })} 
            data={users}
            searchPlaceholder="搜索用户(支持姓名、工号、用户名、部门、角色等)"
          />
        </CardContent>
      </Card>

      <UserDialog
        open={openAddEditDialog}
        onOpenChange={setOpenAddEditDialog}
        user={selectedUser}
      />

      <DeleteDialog
        open={openDeleteDialog}
        onOpenChange={setOpenDeleteDialog}
        onConfirm={handleConfirmDelete}
        title="删除用户"
        description={`确定要删除用户 "${selectedUser?.name}" 吗？此操作不可撤销。`}
      />
    </div>
  )
} 